﻿//-----------------------------------------------------------------------
// <copyright file="ESClientProvider.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: ESClientProvider.cs
// * history : created by qinchaoyue 2017-12-20 05:46:07
// </copyright>
//-----------------------------------------------------------------------

using Nest;
using System;

namespace Slwy.Logger.Implements.Elasticsearch
{
    using Microsoft.Extensions.Options;

    using Slwy.Logger.Models;

    public class ESClientProvider
    {
        private readonly IOptions<LogOptions> _logOptions;

        public ESClientProvider(IOptions<LogOptions> logOptions)
        {
            this._logOptions = logOptions;
        }

        public ElasticClient Client { get; private set; }

        public string DefaultIndex { get; private set; }

        public void EnsureIndexWithMapping<T>(string indexName = null, Func<PutMappingDescriptor<T>, PutMappingDescriptor<T>> customMapping = null) where T : class
        {
            if (String.IsNullOrEmpty(indexName)) indexName = this.DefaultIndex;

            // Map type T to that index
            this.Client.ConnectionSettings.DefaultIndices.Add(typeof(T), indexName);

            // Does the index exists?
            var indexExistsResponse = this.Client.IndexExists(new IndexExistsRequest(indexName));
            if (!indexExistsResponse.IsValid) throw new InvalidOperationException(indexExistsResponse.DebugInformation);

            // If exists, return
            if (indexExistsResponse.Exists) return;

            // Otherwise create the index and the type mapping
            var createIndexRes = this.Client.CreateIndex(indexName);
            if (!createIndexRes.IsValid) throw new InvalidOperationException(createIndexRes.DebugInformation);

            var res = this.Client.Map<T>(m =>
                {
                    m.AutoMap().Index(indexName);
                    if (customMapping != null) m = customMapping(m);
                    return m;
                });

            if (!res.IsValid) throw new InvalidOperationException(res.DebugInformation);
        }

    }
}
